using System;
using System.Windows.Forms;
using System.Threading;

namespace Fader
{
	/// <summary>
	/// Summary description for FadeClass.
	/// </summary>	
		
	public enum FadeTypes
	{
		FadeIn,
		FadeOut
	}		
	
	public class FadeClass
	{		
		private static System.Windows.Forms.Form formToFade;
		private static int fadeInterval = 2; //sets the default fading interval
		private static Thread myThread;
		private static bool waitWhileFading = true; 

		public FadeClass()
		{
			//
			// TODO: Add constructor logic here
			//
		}

		private static void StartFadeIn()
		{
			formToFade.Opacity = 0;

			for (int i = 0; i <= 100; i += fadeInterval)
			{
				formToFade.Opacity = Convert.ToDouble(i) / 100;
				formToFade.Refresh();
			}
		}

		private static void StartFadeOut()
		{
			formToFade.Opacity = 1;

			for (int i = 100; i >= 0; i -= fadeInterval)
			{
				formToFade.Opacity = Convert.ToDouble(i) / 100;
				formToFade.Refresh();
			}
		}

		/// <summary>
		/// Fades the specified form according to the fade type specified.
		/// </summary>	
		public static void Fade(FadeTypes type)
		{
			ThreadStart myThreadDelegate;
			
			if (type == FadeTypes.FadeIn)
				myThreadDelegate = new ThreadStart(StartFadeIn);
			else
				myThreadDelegate = new ThreadStart(StartFadeOut);

			myThread = new Thread(myThreadDelegate);
			myThread.Start();

			if (waitWhileFading) 
				myThread.Join();
		}

		/// <summary>
		/// Sets or gets the System.Windows.Forms.Form to Fade.
		/// </summary>
		public static Form FormToFade
		{
			get
			{
				return formToFade;
			}
			set
			{
				formToFade = value;
			}
		}
		/// <summary>
		/// Sets the fading interval, has to be larger then 0 and less the 100.
		/// </summary>
		public static int FadeInterval
		{
			get
			{
				return fadeInterval;
			}
			set
			{
				if (((100 % value) == 0) && (value > 0) && (value < 100))
					fadeInterval = value;
			}
		}

		/// <summary>
		/// Indicates whether or not the calling thread should wait until the fading process is finished.
		/// </summary>
		public static bool WaitWhileFading
		{
			get
			{
				return waitWhileFading;
			}

			set
			{
				waitWhileFading = value;
			}
		}
	}
}
